﻿//-----------------------------------------------------------------------
// <copyright file="NotifyIconTextFix.cs" company="Redmist">
//     Copyright (c) Damien T Smith. All rights reserved.
// </copyright>
// <author>Damien Smith</author>
//-----------------------------------------------------------------------

namespace Redmist.UsageMonitor.View
{
    using System;
    using System.Reflection;
    using System.Windows.Forms;

    /// <summary>Contains a fix for the 64 character NotifyIcon text limit problem in .NET.</summary>
    public class NotifyIconTextFix
    {
        /// <summary>Sets the text for the specified NotifyIcon up to 127 characters in length.</summary>
        /// <param name="notifyIcon">A System.Windows.Forms.NotifyIcon representing the NotifyIcon for which to set the text.</param>
        /// <param name="text">A System.String representing the text to set for the NotifyIcon.</param>
        public static void SetNotifyIconText(NotifyIcon notifyIcon, string text)
        {
            if (text.Length > 127)
            {
                text = text.Substring(0, 127);
            }

            Type type = typeof(NotifyIcon);
            const BindingFlags Hidden = BindingFlags.NonPublic | BindingFlags.Instance;
            FieldInfo textField = type.GetField("text", Hidden);
            if (textField == null)
            {
                return;
            }
            
            textField.SetValue(notifyIcon, text);

            FieldInfo addedField = type.GetField("added", Hidden);
            if (addedField == null)
            {
                return;
            }

            if ((bool)addedField.GetValue(notifyIcon))
            {
                type.GetMethod("UpdateIcon", Hidden).Invoke(notifyIcon, new object[] { true });
            }
        }
    }
}
